import os
from functools import lru_cache
from pathlib import Path
from typing import Dict

from pydantic import Field, MySQLDsn, RedisDsn
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """
    应用配置类，用于管理应用程序的各种配置项
    通过 pydantic-settings 从环境变量和 .env 文件中加载配置
    """
    model_config = SettingsConfigDict(
        env_file=[".env", f".env.{os.getenv('ENV', 'dev')}"],
        env_file_encoding="utf-8",
        extra="ignore"
    )

    # FastAPI 服务自身配置
    app_name: str = Field(default="python-server", env="APP_NAME")
    app_version: str = Field(default="1.0.0", env="APP_VERSION")
    app_host: str = Field(default="", env="APP_HOST")
    app_port: int = Field(default=8000, env="APP_PORT")

    # swagger 配置
    swagger_title: str = Field(default="Python Server", env="SWAGGER_TITLE")
    swagger_description: str = Field(default="Python Server", env="SWAGGER_DESCRIPTION")
    swagger_terms_of_service: str = Field(default="", env="SWAGGER_TERMS_OF_SERVICE")
    swagger_contact: Dict[str, str] = Field(default={
        "name": "GCC",  # 联系人名称 必填
        "url": "https://gitee.com/xia5800",  # 联系人网址 必填
        "email": "123456@bestgcc.cn"  # 联系人邮箱 必填
    }, env="SWAGGER_CONTACT")
    swagger_license: Dict[str, str] = Field(default={"name": "MIT License", "url": "https://mit-license.org/"},
                                            env="SWAGGER_LICENSE")
    swagger_openapi_url: str = Field(default="/openapi.json", env="SWAGGER_OPENAPI_URL")
    swagger_servers_item: list = Field(default=[{"url": "http://127.0.0.1:8080"}], env="SWAGGER_SERVERS_ITEM")
    swagger_docs_url: str = Field(default="/swagger-ui.html", env="SWAGGER_DOCS_URL")

    # 日志配置
    log_path: str = Field(default="./logs", env="LOG_PATH")  # 文件日志的 输出路径
    log_rotation: str = Field(default="00:00", env="LOG_INTERVAL")  # 日志轮转时间
    log_retention: int = Field(default=3, env="LOG_RETENTION")  # 文件日志的 保留天数

    # 数据库 配置
    database_url: MySQLDsn = Field(default="", env="DATABASE_URL")
    database_log: bool = Field(default=True, env="DATABASE_LOG")
    database_pool_size: int = Field(default=10, env="DATABASE_POOL_SIZE")

    # Redis 配置
    redis_url: RedisDsn = Field(default="", env="REDIS_URL")
    redis_max_connections: int = Field(default=10, env="REDIS_MAX_CONNECTIONS")

    # Nacos 配置
    nacos_server_address: str = Field(default="127.0.0.1:8848", env="NACOS_SERVER_ADDRESS")
    nacos_username: str = Field(default="nacos", env="NACOS_USERNAME")
    nacos_password: str = Field(default="nacos", env="NACOS_PASSWORD")
    nacos_namespace: str = Field(default="", env="NACOS_NAMESPACE")
    nacos_group: str = Field(default="DEFAULT_GROUP", env="NACOS_GROUP")
    instance_ip: str = Field(default="127.0.0.1", env="APP_INSTANCE_IP")
    instance_weight: float = Field(default=1.0, env="APP_INSTANCE_WEIGHT")

    # 安全框架配置
    sa_token_white_list: list | None = Field(default=[], env="SA_TOKEN_WHITE_LIST")
    sa_token_active_timeout: int = Field(default=-1, env="SA_TOKEN_ACTIVE_TIMEOUT")
    sa_token_dynamic_active_timeout: bool = Field(default=False, env="SA_TOKEN_DYNAMIC_ACTIVE_TIMEOUT")
    sa_token_auto_renew: bool = Field(default=True, env="SA_TOKEN_AUTO_RENEW")

@lru_cache # 避免重复创建配置实例
def get_settings():
    """
    获取缓存的配置实例，依赖注入用
    :return:
    """
    return Settings()

# 获取配置实例，用于在整个应用中访问配置
settings = get_settings()

# 初始化临时目录, 用于存放ip2region.xdb文件
TEMP_DIR = Path("temp")
TEMP_DIR.mkdir(exist_ok=True)

# 默认的路由白名单
default_router_white_list: list = [
    # swagger相关
    '/swagger-ui.html',
    '/swagger-ui/**',
    '/**/v3/api-docs',
    '/v3/api-docs/**',
    '/**/v3/api-docs/**',
    '/webjars/**',
    '/favicon.ico',
]
